const express = require('express')
const app = express()

const session = require('express-session')
app.use(
  session({
    secret: 'ZhangZhiqi',
    resave: false,
    saveUninitialized: true
  })
)

/**
 * http://127.0.0.1/api/login
 *  ● username  admin
 *  ● password  123456
 */
app.post('/api/login', express.urlencoded({ extended: false }), (req, res) => {
  if (req.body.username === 'admin' && req.body.password === '123456') {
    // 通过 req.session 操作 session
    req.session.userInfo = req.body
    res.send({ status: 0, msg: '登录成功' })
  } else {
    res.send({ status: 1, msg: '登录失败' })
  }
})

/**
 * http://127.0.0.1/api/logout
 */
app.get('/api/logout', (req, res) => {
  // 清除 session
  req.session.destroy()
  res.send({ status: 0, msg: '退出登录成功' })
})

/**
 * http://127.0.0.1/api/getUserInfo
 */
app.get('/api/getUserInfo', (req, res) => {
  console.log(JSON.stringify(req.session))
  if (req.session.userInfo) {
    res.send({ status: 0, msg: '成功', data: req.session.userInfo })
  } else {
    res.status(401)
    res.send()
  }
})

app.listen(80, () => {
  console.log('Server running at http://127.0.0.1')
})
